package client.controller;

import java.rmi.Naming;
import java.util.Collection;

import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.vecmath.Quat4d;
import javax.vecmath.Vector3d;

import server.controller.Universe3DControllerRemoteInterface;

import com.sun.j3d.utils.picking.PickCanvas;
import com.sun.j3d.utils.universe.ViewingPlatform;

import client.Client;
import client.model.Universe3D;
import client.presentation.Object3DPresentation;
import client.presentation.Universe3DPresentation;
import client.presentation.Viewpoint3DPresentation;

public class Universe3DController {
	
	private Universe3D abstraction;
	private Universe3DPresentation presentation;
	
	public Universe3DController() {
		abstraction = new Universe3D();
		presentation = new Universe3DPresentation(this);
	}
	
	//Informations recues depuis le multicast, met a jour l'objet concerne ou le cree
	public void objectUpdateTransform (String name, String vrml, Vector3d pos, Quat4d quat) {
		Virtual3DController object = abstraction.getObject(name);
		if(object == null) {
			object = abstraction.getViewpoint(name);
			if(object == null) {
				addObject(new Object3DController(name));
			}
			else {
				object.update(pos, quat);
			}
		}
		else {
			object.update(pos, quat);
		}
	}
	
	public Canvas3D getCanvas() {
		return presentation.getCanvas();
	}
	
	public PickCanvas getPickCanvas() {
		return presentation.getPickCanvas();
	}
	
	public BranchGroup getScene() {
		return presentation.getScene();
	}
	
	public void addObject(Virtual3DController o) {
		if(!abstraction.contains(o.getName())) {
			abstraction.addObject(o);
			presentation.addObject((Object3DPresentation)o.getPresentation());
		}
	}
	
	public void addViewpoint(Virtual3DController v) {
		abstraction.addViewpoint(v);
	}
	
	public Virtual3DController getSelectedViewpoint() {
		return abstraction.getSelectedViewpoint();
	}
	
	public Collection<Virtual3DController> getAllViewpoints() {
		return abstraction.getViewpoints();
	}
	
	public boolean selectViewpoint(Virtual3DController v) {
		boolean updated = abstraction.selectViewpoint(v);
		if(updated) {
			( (Viewpoint3DPresentation)(this.getSelectedViewpoint().getPresentation()) ).update();
		}
		return updated;
	}
	
	public ViewingPlatform getViewingPlatform() {
		return presentation.getViewingPlatform();
	}
	
	public void createObject(String name, Vector3d position, Quat4d orientation, String vrml) {
		try {
			Universe3DControllerRemoteInterface server = (Universe3DControllerRemoteInterface) Naming.lookup(Client.lookupName);
			
			server.addObject3DController(name, position, orientation, vrml);
			System.out.println("Objet cree");
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

}
